<?php

namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Models\Shop\Order, App\Models\Shop\Cart,  App\Models\Shop\Product, App\Models\Shop\OrderProduct,App\Models\Shop\Express;
use App\Models\Shop\Customer;
use App\Models\Shop\OrderAddress,App\Models\Shop\Address;

class OrderController extends Controller
{
    function index(Request $request)
    {

        $orders = Order::with('order_products.product', 'customer', 'address')
            ->orderBy('created_at', 'desc')
            ->get();
        $order_status = config('shop.order_status');
        //return $orders[0]->order_products[0]->num;
        return view('home.order')->with('orders',$orders)->with('order_status',$order_status);
    }
    public function show($id)
    {
        $order = Order::with('address', 'express', 'customer', 'order_products.product')->find($id);
        //return $order;
        return view('home.order_list')->with('order', $order);
    }

    /**
     * 下单
     * @return mixed
     */
    function checkout()
    {

        $carts = Cart::with('product')->where('customer_id', session('customer.id'))->get();

        //如果购物车中没有商品,跳回购物车页面
        if ($carts->isEmpty()) {
            return redirect('/cart');
        }
        $address = Address::find(session('customer.address_id'));
        //return session('customer.address_id');
        //return $address;
        return view('home.checkout')
            ->with('carts', $carts)
            ->with('count', Cart::count_cart($carts))
            ->with('address', $address);
    }

    function destroy($id)
    {
        //查出对应的商品,并将库存还回去
        $order = Order::with('order_products')->find($id);
        foreach ($order->order_products as $order_product) {
            $product = Product::find($order_product->product_id);
            //如果不是无限库存
            if ($product->stock != '-1') {
                Product::where('id', $order_product->product_id)->increment('stock', $order_product->num);
            }
        }

        //删除订单商品
        OrderProduct::where('order_id', $id)->delete();
        //删除订单地址
        OrderAddress::where('order_id', $id)->delete();
        Order::destroy($id);
        return redirect('/customer');
    }
    //生成订单
    function store(Request $request)
    {
        $count = Cart::count_cart();
        $total_price = $count['total_price'];
        $data = [];

        DB::beginTransaction();
        try {
            //生成订单
            $order = Order::create([
                'customer_id' => session('customer.id'),
                'total_price' => $total_price,
                'status' => 1
            ]);

            //订单地址
            $address = OrderAddress::find($request->address_id);
            $order->address()->create([
                'province' => $address['province'],
                'city' => $address['city'],
                'area' => $address['area'],
                'detail' => $address['detail'],
                'name' => $address['name'],
                'tel' => $address['tel'],
            ]);

            $carts = Cart::with('product')->where('customer_id', session('customer.id'))->get();
            foreach ($carts as $cart) {
                //判断库存是否足够
                if ($cart->product->stock != '-1' and $cart->product->stock - $cart->num < 0) {
                    throw new \Exception('商品' . $cart->product->name . ", 目前仅剩下" . $cart->product->stock . " 件. \n请返回购物车, 修改订单后再下单!");
                }

                //削减库存数量
                if ($cart->product->stock != '-1') {
                    $cart->product->decrement('stock', $cart->num);
                }

                //插入订单商品表
                $order->order_products()->create([
                    'product_id' => $cart->product_id,
                    'num' => $cart->num
                ]);
            }

            //清空购物车
            Cart::with('product')->where('customer_id', session('wechat.customer.id'))->delete();

        } catch (\Exception $e) {
//            echo $e->getMessage();

            DB::rollback();
            $data['status'] = 0;
            $data['info'] = $e->getMessage();
            return $data;
        }
        DB::commit();

        $data['status'] = 1;
        $data['order_id'] = $order->id;
        return $data;
    }
    function show_pay($id)
    {
        $order = Order::with('address')->find($id);
        return view('home.show_pay')->with('order', $order);
    }
}
